package com.flame.workflow.ru.engine.handler;

import com.flame.workflow.constants.RuntimeConstants;
import com.flame.workflow.constants.TaskConstants;
import com.flame.workflow.constants.UserTaskConstants;
import com.flame.workflow.ru.engine.context.RuntimeContext;
import com.flame.workflow.ru.entity.Instance;
import com.flame.workflow.ru.entity.Task;
import com.flame.workflow.ru.entity.UserTask;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author wuxintong😺😺😺
 * @since 2023/6/6
 */
@Service("workflow-start-task-handler")
public class StartTaskHandler extends AbstractTaskHandler {

    @Override
    public String runTask(RuntimeContext runtimeContext) {
        Instance instance = runtimeContext.getInstance();
        Task task = runtimeContext.getTask();

        // 补一个 userTask 进去
        UserTask userTask = userTaskService.getByTaskIdAndUserId(task.getTaskId(), instance.getUserId());
        if (ObjectUtils.isEmpty(userTask)) {
            userTaskService.addUserTask(instance.getInstanceId(), task.getTaskId(), instance.getUserId());
            userTaskService.completeByTaskIdAndUserId(task.getTaskId(), instance.getUserId(), UserTaskConstants.USER_TASK_STATUS_COMPLETE_SUBMIT, false);
        }

        return RuntimeConstants.RUNTIME_STATUS_COMPLETE;
    }

    @Override
    public String taskType() {
        return TaskConstants.TASK_TYPE_START;
    }
}
